package com.xjlsoft.weather.task;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjlsoft.weather.common.util.DataUtil;
import com.xjlsoft.weather.config.ApplicationContextProvider;
import com.xjlsoft.weather.entity.ExceptionLog;
import com.xjlsoft.weather.entity.QueryLog;
import com.xjlsoft.weather.entity.RequestApi;
import com.xjlsoft.weather.entity.WeatherTask;
import com.xjlsoft.weather.enums.RequestApiEnum;
import com.xjlsoft.weather.enums.WeatherTaskEnum;
import com.xjlsoft.weather.exception.WeatherException;
import com.xjlsoft.weather.mapper.ExceptionLogMapper;
import com.xjlsoft.weather.mapper.RequestApiMapper;
import com.xjlsoft.weather.mapper.WeatherTaskMapper;
import com.xjlsoft.weather.service.WeatherTaskJob;
import com.xjlsoft.weather.service.WeatherTaskService;

/**
 * 任务 01
 *
 * @author 码农猿
 */
public class GroundPreTask implements WeatherTaskJob {
	
	
	/**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(GroundPreTask.class);

    /**
     * 可重入锁
     */
    //private ReentrantLock lock = new ReentrantLock();
    
    private  WeatherTaskService weatherTaskService;
    
    
	private RequestApiMapper requestApiMapper;
	
	private WeatherTaskMapper  weatherTaskMapper;
	
	private ExceptionLogMapper exceptionLogMapper;
    
    /**
     * 处理地面数据
     * */
    @Override
    public void run() {
    	logger.info(">>>>>>>>>>>>开始 处理   地面 数据           GroundDataTask   当前线程名称 {}", Thread.currentThread().getName());
    	
    	
    	//logger.info(">>>>>> 开始任务  加锁");
    	//lock.lock();
    	requestApiMapper=ApplicationContextProvider.getBean(RequestApiMapper.class);
    	
    	weatherTaskMapper=ApplicationContextProvider.getBean(WeatherTaskMapper.class);
    	
    	exceptionLogMapper=ApplicationContextProvider.getBean(ExceptionLogMapper.class);

        RequestApi requestapi=requestApiMapper.selectById(RequestApiEnum.groundPre.getValue());
        
        WeatherTask wt=weatherTaskMapper.getByKey(WeatherTaskEnum.GroundPreTask.getValue());
       
        if(requestapi==null){
        	logger.error("未查询到RequestApi数据,request_api_id="+RequestApiEnum.groundPre.getValue());
        }
        try {

        	//logger.info(">>>>>>>>>>睡眠27秒>>>>>>>");
        	//Thread.currentThread();
			//Thread.sleep(1000*27);
        	weatherTaskService=ApplicationContextProvider.getBean(WeatherTaskService.class);
        	
        	
        	Map<String,Object> mp=weatherTaskService.createQuerylogMinData(requestapi, wt);
        	
        	if(!(mp == null)){
        		
        		QueryLog ql=(QueryLog)mp.get("querylog");
            	boolean initFlag=(boolean)mp.get("initFlag");
            	boolean stopTaskFlag=(boolean)mp.get("stopTaskFlag");
            	
            	if(ql!=null){
            		weatherTaskService.saveGroundProJson(ql, requestapi, initFlag);
            	}
            	
            	
            	if(stopTaskFlag){
            		//先开启在关联定时任务   在关闭 定时任务 否则 获取不到连接
            		boolean flag2 = weatherTaskService.startByWeatherTask(wt);

        			logger.info("******************************************************************************");
        			logger.info("***********开启 关联 定时任务:(" + weatherTaskService.getByWeatherTask(wt).getValue() + ") 开启状态：" + flag2);
        			logger.info("******************************************************************************");
            		
        			
            		boolean flag = weatherTaskService.stop(wt.getTask_key());

        			logger.info("==============================================================================");
        			logger.info("==============历史数据统计完毕       关闭定时任务:(" + wt.getTask_desc() + ") 关闭状态：" + flag);
        			logger.info("==============================================================================");

            	}
        	}
        	
        	
        	
        	
		} catch (WeatherException we) {
			logger.error("创建      数据    类型，请求数据异常",we);
			//保存失败请求的 原因  task_log表
			ExceptionLog ex=new ExceptionLog();
			ex.setExceptionId(IdWorker.getIdStr());
			ex.setCreateTime(DataUtil.getCurrenTimestamp());
			ex.setMessage(we.toString());
			StackTraceElement[] st=we.getStackTrace();
			if(st !=null){
				ex.setCodeStr(st[0].toString());
			}
			exceptionLogMapper.insert(ex);
		}  catch (Exception e) {
			e.printStackTrace();
		}
        logger.info(">>>>>>>>>>>>结束 处理   地面 数据            GroundDataTask   当前线程名称 {}", Thread.currentThread().getName());
    }
}